package com.wen.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wen.edu.entity.EduCourse;
import com.wen.edu.entity.EduCourseDescription;
import com.wen.edu.entity.vo.CourseInfoVO;
import com.wen.edu.entity.vo.CoursePublishVo;
import com.wen.edu.entity.vo.front.FrontCourseInfoVO;
import com.wen.edu.entity.vo.front.FrontCourseQueryVO;
import com.wen.edu.mapper.EduCourseMapper;
import com.wen.edu.service.EduChapterService;
import com.wen.edu.service.EduCourseDescriptionService;
import com.wen.edu.service.EduCourseService;
import com.wen.edu.service.EduVideoService;
import com.wen.servicebase.exception.BusinessException;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author wen
 * @since 2021-05-29
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {
    @Resource
    private EduCourseDescriptionService eduCourseDescriptionService;
    @Resource
    private EduVideoService eduVideoService;
    @Resource
    private EduChapterService eduChapterService;

    /**
     * 添加课程基本信息
     *
     * @param courseInfoVO 要添加的课程基本信息
     * @return 添加成功后的课程ID
     */
    @Override
    public String addCourseInfo(CourseInfoVO courseInfoVO) {
//      向课程表中添加课程基本信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVO, eduCourse);
        int insert = baseMapper.insert(eduCourse);
        if (insert == 0) {
            throw new BusinessException("课程基本信息添加失败");
        }
//        向课程描述表中添加课程简介
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        BeanUtils.copyProperties(courseInfoVO, eduCourseDescription);
//        让课程表和课程描述表根据两者的id一致来进行关联,
//        需要修改EduCourseDescription实体类中id默认的生成策略（由自动生成改为手动设置）
        eduCourseDescription.setId(eduCourse.getId());
        boolean save = eduCourseDescriptionService.save(eduCourseDescription);
        if (!save) {
            throw new BusinessException("课程描述信息添加失败");
        }
        return eduCourse.getId();
    }

    /**
     * 根据课程ID查询添加至数据库中的课程基本信息
     *
     * @param courseId 课程ID
     * @return result of operation
     */
    @Override
    public CourseInfoVO getCourseInfo(String courseId) {
//        先查询course表中的信息，
        EduCourse eduCourse = this.getById(courseId);
//        再查询course-description中的描述信息
        EduCourseDescription eduCourseDescription = eduCourseDescriptionService.getById(courseId);
//        新建 CourseInfoVO对象，并复制属性，最后返回
        CourseInfoVO courseInfoVO = new CourseInfoVO();
        BeanUtils.copyProperties(eduCourse, courseInfoVO);
        BeanUtils.copyProperties(eduCourseDescription, courseInfoVO);
        return courseInfoVO;
    }

    /**
     * 修改课程信息
     *
     * @param courseInfoVO 要添加的课程信息
     */
    @Override
    public void updateCourseInfo(CourseInfoVO courseInfoVO) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVO, eduCourse);
        int i = baseMapper.updateById(eduCourse);
        if (i == 0) {
            throw new BusinessException("课程基本信息修改失败");
        }
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setId(courseInfoVO.getId());
        eduCourseDescription.setDescription(courseInfoVO.getDescription());
        boolean b = eduCourseDescriptionService.updateById(eduCourseDescription);
        if (!b) {
            throw new BusinessException("课程描述信息修改失败");
        }
    }

    /**
     * 根据课程ID查询确认课程信息
     *
     * @param courseId 课程ID
     * @return result of operation
     */
    @Override
    public CoursePublishVo getPublishCourseInfo(String courseId) {
        return baseMapper.getPublishCourseInfoById(courseId);
    }

    /**
     * 删除课程信息(包括课程基本信息，课程大纲，课程视频等相关信息)
     *
     * @param courseId 课程id
     */
    @Override
    public void removeAllCourseInfo(String courseId) {
//      先删除课程小节
        eduVideoService.removeByCourseId(courseId);
//        再删除课程大纲
        eduChapterService.removeByCourseId(courseId);
//        删除课程描述
        eduCourseDescriptionService.removeById(courseId);
//        最后删除课程本身信息
        int i = baseMapper.deleteById(courseId);
        if (i == 0)
            throw new BusinessException("课程删除失败~~~");
    }

    /**
     * 查询前台显示的热门课程
     *
     * @return list
     */
    @Override
    @Cacheable(value = "courses", key = "'selectHotCourses'")
    public List<EduCourse> selectHotCourses() {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        wrapper.last("limit 8 ");
        return baseMapper.selectList(wrapper);
    }

    /**
     * 带条件分页查询前台课程信息
     *
     * @param pageCourse         分页
     * @param frontCourseQueryVO 条件
     * @return result of operation
     */
    @Override
    public Map<String, Object> pageFrontCourse(Page<EduCourse> pageCourse, FrontCourseQueryVO frontCourseQueryVO) {
        String countSort = frontCourseQueryVO == null ? null : frontCourseQueryVO.getBuyCountSort();
        String priceSort = frontCourseQueryVO == null ? null : frontCourseQueryVO.getPriceSort();
        String gmtCreateSort = frontCourseQueryVO == null ? null : frontCourseQueryVO.getGmtCreateSort();
        String subject_parent_id = frontCourseQueryVO == null ? null : frontCourseQueryVO.getSubjectParentId();
        String subject_id = frontCourseQueryVO == null ? null : frontCourseQueryVO.getSubjectId();
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        //判断条件值是否为空，不为空拼接
        if (!StringUtils.isEmpty(subject_parent_id)) { //一级分类
            wrapper.eq("subject_parent_id", subject_parent_id);
        }
        if (!StringUtils.isEmpty(subject_id)) { //二级分类
            wrapper.eq("subject_id", subject_id);
        }
        if (!StringUtils.isEmpty(countSort)) { //关注度
            wrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(gmtCreateSort)) { //最新
            wrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(priceSort)) {//价格
            wrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageCourse, wrapper);

        List<EduCourse> records = pageCourse.getRecords();
        long current = pageCourse.getCurrent();
        long pages = pageCourse.getPages();
        long size = pageCourse.getSize();
        long total = pageCourse.getTotal();
        boolean hasNext = pageCourse.hasNext();//下一页
        boolean hasPrevious = pageCourse.hasPrevious();//上一页

        //把分页数据获取出来，放到map集合
        Map<String, Object> map = new HashMap<>();
        map.put("records", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        //map返回
        return map;
    }

    /**
     * 根据课程id查询课程信息(多表查询)
     *
     * @param courseId 课程id
     * @return VO对象
     */
    @Override
    public FrontCourseInfoVO getFrontCourseInfo(String courseId) {
        return baseMapper.getFrontCourseInfo(courseId);
    }
}
